package org.apache.rocketmq.example.quickstart.transaction;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 事务消费者
 */
public class TransactionConsumer {
    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group-1");
        consumer.setNamesrvAddr("39.107.66.31:9876");
        consumer.subscribe("topic-10", "*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageExtList, ConsumeConcurrentlyContext context) {
                try {
                    for (MessageExt messageExt : messageExtList) {
                        System.out.println("执行本地事务成功!transactionId = " + messageExt.getTransactionId());
                        System.out.println(new String(messageExt.getBody()));
                    }
                } catch (Exception e) {
                    // 消费失败，放入重试队列
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                // 消费成功，发送ACK确认
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 启动消费者
        consumer.start();
        System.out.println("消费者已启动");
    }
}
